//
//  AirPlayViewController.swift
//  MyVideo
//
//  Created by han on 2021/4/22.
//

import UIKit
import AVKit

class AirPlayViewController: UIViewController {
   
    @IBOutlet weak var playVideoButton: UIButton!
    
    @IBAction func playVideoButtonPressed(_ sender: Any) {
        playbackLongFormVideoIntegratingAirPlay()
    }
    // Integrating AirPlay for Long-Form Video
    func playbackLongFormVideoIntegratingAirPlay()  {
        AVAudioSession.sharedInstance().prepareRouteSelectionForPlayback { (shouldStartPlayback, routeSelection) in
            guard shouldStartPlayback else {
                print("Cancelling playback")
                return
            }
            switch routeSelection {
            case .local, .external:
                guard let url = URL(string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_ts/master.m3u8") else { return }
                do {
                    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
                } catch  {
                    print("Error setting audio session category and mode: \(error)")
                }
                let player = AVPlayer(url: url)
                if routeSelection == .local {
                    print("Play locally")
                    let playerViewController = AVPlayerViewController()
                    playerViewController.player = player
                    self.present(playerViewController, animated: true, completion: nil)
                    player.play()
                } else {
                    print("Play externally")
                    if let remoteControlVC = UIStoryboard(name: "SimplePlayer", bundle: nil).instantiateViewController(identifier: RemoteControlViewController.storyboardID) as? RemoteControlViewController {
                        remoteControlVC.player = player
                        self.present(remoteControlVC, animated: true, completion: nil)
                        player.play()
                    }
                }
            case .none:
                fallthrough
            default:
                print("Cancelling playback")
            }
        }
    }
}
